package com.example.springboot.common;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 分页查询参数
 */
@ToString
public class PageParam<T> extends Page<T> {
    /**
     * 每页显示条数，默认 10，max 100
     */
    private long size = 10;

    /**
     * 当前页
     */
    private long current = 1;

    /**
     * 查询数据列表
     */
    private List<T> records;

    /**
     * 总数
     */
    private long total = 0;

    /**
     * 倒序排序字段
     */
    private String[] descColumn;

    /**
     * 升序排序字段
     */
    private String[] ascColumn;


    @Override
    public long getSize() {
        return size;
    }

    @Override
    public Page<T> setSize(long size) {
        int maxSize = 100;
        if (size > maxSize) {
            this.size = maxSize;
        } else {
            this.size = size;
        }
        return this;
    }

    @Override
    public long getCurrent() {
        return current;
    }

    @Override
    public Page<T> setCurrent(long current) {
        this.current = current;
        return this;
    }

    @Override
    public List<T> getRecords() {
        return records;
    }

    @Override
    public Page<T> setRecords(List<T> records) {
        this.records = records;
        return this;
    }

    @Override
    public long getTotal() {
        return total;
    }

    @Override
    public Page<T> setTotal(long total) {
        this.total = total;
        return this;
    }

    public void setDescColumn(String[] descColumn) {
        this.descColumn = descColumn;
        this.orders = Optional.ofNullable(this.orders).orElse(new ArrayList<OrderItem>());
        for (String column : descColumn){
            if (StringUtils.isNotBlank(column)){
                OrderItem orderItem = OrderItem.desc("id");
                this.orders.add(orderItem);
            }
        }
    }

    public void setAscColumn(String[] ascColumn) {
        this.ascColumn = ascColumn;
        this.orders = Optional.ofNullable(this.orders).orElse(new ArrayList<OrderItem>());
        for (String column : ascColumn){
            if (StringUtils.isNotBlank(column)){
                OrderItem orderItem = OrderItem.asc(column);
                this.orders.add(orderItem);
            }
        }
    }

    @Override
    public void setOrders(List<OrderItem> orders) {
        this.orders = orders;
    }

    @Override
    public String toString() {
        return "PageParam{" +
                "size=" + size +
                ", current=" + current +
                ", records=" + records +
                ", total=" + total +
                ", descColumn=" + Arrays.toString(descColumn) +
                ", ascColumn=" + Arrays.toString(ascColumn) +
                '}';
    }

}
